#include "http.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QMap>
#include <QNetworkReply>

Http::Http(QObject *parent) : QObject(parent)
{

}

bool Http::post_sync(QString url, QMap<QString, QString> header, QByteArray requestData, QByteArray &replyData)
{
    QNetworkAccessManager manager;
    //请求对象
    QNetworkRequest request;
    request.setUrl(url);

    QMapIterator<QString,QString> it(header);
    while(it.hasNext())
    {
        it.next();
        request.setRawHeader(it.key().toLatin1(),it.value().toLatin1());
    }

    QNetworkReply *reply= manager.post(request,requestData);
    //避免网络时延
    QEventLoop l;
    connect(reply,&QNetworkReply::finished,&l,&QEventLoop::quit);
    l.exec();

    if(reply!=nullptr && reply->error()==QNetworkReply::NoError){
        replyData=reply->readAll();
        qDebug()<<replyData;
        return true;
    }
    else {
        qDebug()<<"请求失败";
        return  false;
    }

}
